<template>
  <div>
    <!--搜索表单-->
    <div style="margin: 10px 0">
      <el-input prefix-icon="el-icon-user" style="width: 240px;" placeholder="请输入姓名"
                v-model="params.name"></el-input>
      <el-input prefix-icon="el-icon-phone-outline" style="width: 240px;margin-left: 5px" placeholder="请输入联系方式"
                v-model="params.phone"></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="load"><i class="el-icon-search"></i>搜索</el-button>
      <el-button style="margin-left: 5px" type="warning" @click="reset"><i class="el-icon-refresh"></i>重置</el-button>
    </div>
    <!--批量删除-->
    <el-popconfirm
        confirm-button-text='确定'
        cancel-button-text='我再想想'
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
    >
      <el-button type="danger" slot="reference" style="margin-bottom:10px">批量删除 <i class="el-icon-remove-outline"></i>
      </el-button>
    </el-popconfirm>
    <!--数据表格-->
    <el-table :data="tableDate" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column prop="id" label="编号" width="60px"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100px"></el-table-column>
      <el-table-column prop="username" label="会员卡号"></el-table-column>
      <el-table-column prop="account" label="账户积分" width="80px"></el-table-column>
      <el-table-column prop="age" label="年龄" width="60px"></el-table-column>
      <el-table-column prop="gender" label="性别" width="60px"></el-table-column>
      <el-table-column prop="phone" label="联系方式"></el-table-column>
      <el-table-column prop="address" label="地址" width="60px"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column label="状态">
        <template v-slot="scope">
          <el-switch
              v-model="scope.row.status"
              @change="changeStatus(scope.row)"
              active-color="#13ce66"
              inactive-color="#dfdfdf">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px">
        <template v-slot="scope">

          <!--scope.row就是当前行的数据-->
          <el-button style="margin-right: 5px;" type="success" @click="handleAccount(scope.row)">充值
          </el-button>
          <el-button style="margin-right: 5px;margin-left: 0" type="primary"
                     @click="$router.push('/editUser?id='+scope.row.id)">编辑
          </el-button>

          <template>
            <el-popconfirm title="您确定删除这行数据吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div style="margin-top: 10px">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--充值弹窗-->
    <el-dialog title="充值" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="100px" ref="ruleForm" :rules="rules" style="width: 85%;margin: 0 auto">
        <el-form-item label="当前账户积分" prop="account">
          <el-input disabled v-model="form.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="充值积分" prop="score">
          <el-input v-model="form.score" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAccount">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: 'User',
  data() {
    const checkNumbers = (rule, value, callback) => {   //校验联系方式规则
      value = parseInt(value)
      if (!Number.isInteger(value) || value < 10 || value > 200) {
        callback(new Error('请输入10~200的整数'));
      }
      if (value === null || value === undefined) {
        callback(new Error('请输入大于等于0的整数'));
      }
      callback()
    };
    return {
      tableDate: [],       //1.存放数据
      total: 0,           //总条数
      params: {            //分页模糊查询参数
        pageSize: 10,
        pageNum: 1,
        name: '',
        phone: ''
      },
      multipleSelection: [],
      dialogVisible: false,
      form: {},
      rules: {
        score: [
          {required: true, message: '充值积分不能为空', trigger: 'blur'},
          {validator: checkNumbers, trigger: 'blur'}
        ],
      }
    }
  },
  created() {					//3.前端页面加载数据
    this.load()
  },
  methods: {
    load() {                 //2.请求后台数据
      // fetch('http://localhost:9090/user/list').then(res => res.json()).then(res => {
      //     // console.log(res)
      //     if (res.code==='200'){
      //         console.log(res)
      //         this.tableDate = res.data
      //     }else {
      //         this.$message.error(res.msg)
      //     }
      // })

      request.get('/user/page', {
        params: this.params
      }).then(res => {
        console.log(res.data)
        if (res.code === '200') {
          this.tableDate = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    reset() {               //重置
      this.params = {
        pageSize: 10,
        pageNum: 1,
        name: '',
        phone: ''
      }
      this.load()
    },
    handleSelectionChange(val) {//多选
      // console.log(val)
      this.multipleSelection = val;
    },
    delBatch() { //批量删除
      let ids = this.multipleSelection.map(v => v.id)  //把对象数组变成纯id数组
      request.post('/user/deleteBatch', ids).then(res => {
        if (res.code === '200') {
          this.$notify.success('批量删除成功')
          this.load()
        } else {
          this.$notify.error('批量删除失败')
        }
      })
    },
    handleCurrentChange(pageNum) {      //点击分页按钮触发分页
      // console.log(pageNum)        //打印点击的页码
      this.params.pageNum = pageNum
      this.load()
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.load()
    },
    handleAccount(row) {  //充值
      this.form = JSON.parse(JSON.stringify(row))
      this.load()
      this.dialogVisible = true
    },
    addAccount() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          request.post('/user/account', this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success("充值成功")
              this.dialogVisible = false
              this.load()
            } else {
              this.$notify.error("充值失败")
            }
          })
        }
      })
    },
    del(id) {
      request.delete("/user/delete/" + id).then(res => {
        if (res.code === '200') {
          this.$notify.success("删除成功")
          this.load()
        } else {
          this.$notify.error("删除失败")
        }
      })
    },
    changeStatus(row) {    //更改状态
      request.put('/user/update', row).then(res => {
        if (res.code === '200') {
          this.$notify.success('操作成功！')
          this.load()
        } else {
          this.$notify.error(res.msg)
        }
      })
    },
  }
}
</script>